import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/article',
    component: () => import('@/views/article/index.vue')
  },
  {
    path: '/search',
    component: () => import('@/views/search/index.vue')
  },
  {
    path: '/result',
    component: () => import('@/views/search/result.vue'),
    mate: {
      keepAlive: true
    }
  },
  {
    path: '/layout',
    component: () => import('@/views/layout/index.vue'),
    children: [
      {
        path: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          keepAlive: true
        }
      },
      {
        path: 'ask',
        component: () => import('@/views/ask/index.vue')
      },
      {
        path: 'video',
        component: () => import('@/views/video/index.vue')
      },
      {
        path: 'mine',
        component: () => import('@/views/mine/index.vue'),
        meta: {
          needLogin: true
        }
      },
      {
        path: 'chat',
        component: () => import('@/views/mine/chat.vue'),
        meta: {
          needLogin: true
        }
      },
      {
        path: 'edit',
        component: () => import('@/views/mine/edit.vue'),
        meta: {
          needLogin: true,
          noTab: true
        }
      }
    ]
  },
  {
    path: '*',
    redirect: '/layout/home'
  }
]

const router = new VueRouter({
  routes,
  scrollBehavior: () => {
    return {
      x: 0,
      y: 0
    }
  }
})
router.beforeEach(async (to, from, next) => {
  if (to.meta.needLogin) {
    if (store.state.tokenObj.token) {
      if (store.state.userInfo.id) {
        next()
      } else {
        await store.dispatch('getUserInfo')
        next()
      }
    } else {
      next('/login?back=' + to.fullPath)
    }
  } else {
    next()
  }
})

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}
export default router
